package webscoket

import (
	"mqtt_on_offline/webscoket/impl"
	"net/http"
	"github.com/gorilla/websocket"
	"time"
)

var(
	upgrader = websocket.Upgrader{
		// 允许跨域调用
		CheckOrigin: func(r *http.Request) bool {

			return true
		},
	}
)

var(
	wsConn *websocket.Conn
	err error
	Conn *impl.Connection
	data []byte
)

func WsHandler(writer http.ResponseWriter, request *http.Request){

	if wsConn, err = upgrader.Upgrade(writer, request, nil); err != nil{
		return
	}

	// websocket.Conn
	if Conn, err = impl.InitConnection(wsConn); err != nil {
		goto ERR
	}

	go func() {
		var(
			err error
		)
		for{
			if err = Conn.WriteMessage([]byte("heartbeat")); err != nil {
				return
			}
			time.Sleep(1 * time.Second)
		}

	}()

	for{
		if data, err = Conn.ReadMessage(); err != nil{
			goto ERR
		}
		if err = Conn.WriteMessage(data); err != nil{
			goto ERR
		}
	}

ERR:
	Conn.Close()
}

